package org.wx.io.netty.tcp.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @description: tcp 粘包和拆包
 * @author: wangxun
 * @createDate: 2021/2/22
 * @version: 1.0
 */
@Slf4j
public class TcpServer implements Runnable {
    private InetSocketAddress inetAddress;

    public TcpServer(InetSocketAddress inetAddress) {
        this.inetAddress = inetAddress;
    }

    @Override
    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new TcpServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(inetAddress);
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()){
                        log.info("服务器开启成功，开启地址是{}",future.channel().localAddress());
                    }
                }
            });

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        TcpServer tcpServer = new TcpServer(new InetSocketAddress("127.0.0.1", 1999));
        new Thread(tcpServer).start();
    }
}
